//
//  XYVideoContainerCell.m
//  NemoSDKDemo
//
//  Created by 高超 on 2020/8/12.
//  Copyright © 2020 JackYang. All rights reserved.
//

#import "XYVideoContainerCell.h"
#import "UIColor+XYColor.h"

@interface XYVideoContainerCell ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) NSArray *videos;

@property (nonatomic, strong) NSMutableArray *currentVideos;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, assign) int asId;

@end

@implementation XYVideoContainerCell

- (void)dealloc
{
    //释放video
    for (XYRTCVideoCanvas *video in _currentVideos) {
        [video clear];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _containerView = [[UIView alloc] initWithFrame:DEFAULTFRAME];
//        _containerView.backgroundColor = [UIColor colorWithHexString:@"#22222B"];
//        self.backgroundColor = [UIColor colorWithHexString:@"#22222B"];
        _containerView.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_containerView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChange) name:UIApplicationDidChangeStatusBarOrientationNotification
                                                   object:nil];
        _currentVideos = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)orientationChange {
    [self updateFrame];
}

- (void)updateVideos:(NSArray *)videos index:(NSInteger)index activeSpeakerId:(int)activeSpeakerId {
    _videos = videos;
    _index = index;
    _asId = activeSpeakerId;
    
    [self _setupVideos];
}

- (void)_setupVideos {
    NSMutableArray *allVideos = [NSMutableArray arrayWithArray:_videos];
    NSMutableArray *removeVideos = [NSMutableArray array];
    // 过滤video，更新存在video，保存不存在video
    for (XYRTCVideoCanvas *video in _currentVideos) {
        BOOL found = NO;
        for (NemoLayout *layout in allVideos) {
            if ((layout == _localLayout && video.layout == _localLayout) || [self equalLayout:layout with:video.layout]) {
                XYCustomVideoView *cusView = (XYCustomVideoView *)video.view;
                video.isLocal = layout == _localLayout;
                cusView.isLocalView = layout == _localLayout;
                found = YES;
                video.layout = layout;
                cusView.layout = layout; //更新本地展示的view
                [[XYSDKManager sharedInstance] updateVideo:video]; //更新视频
                [allVideos removeObject:layout];
                break;
            }
        }
        if (!found) {
            [removeVideos addObject:video];
        }
    }
    // 移除不存在video，并且移除View
    for (XYRTCVideoCanvas *video in removeVideos) {
        [_currentVideos removeObject:video];
        [video clear];
        [video.view removeFromSuperview];
    }
    //创建新的video
    for (NSInteger i = 0; i < allVideos.count; i++) {
        XYRTCVideoCanvas *video = [[XYRTCVideoCanvas alloc] init];
        XYCustomVideoView *view = [[XYCustomVideoView alloc] initWithFrame:DEFAULTFRAME];
        video.view = view;
        video.layout = allVideos[i];
        view.layout = allVideos[i];
        if (allVideos[i] == _localLayout && _index < 2) {
            video.isLocal = YES;
            view.isLocalView = YES;
        }
        [[XYSDKManager sharedInstance] setupVideo:video]; //创建视频
        [self.containerView addSubview:view];
        if (video.isLocal) {
            [self.currentVideos insertObject:video atIndex:0];
        }else {
            [self.currentVideos addObject:video];
        }
    }
    
    XYRTCVideoCanvas *asCanva = nil;
    for (XYRTCVideoCanvas *canva in self.currentVideos) {
        if ([canva.layout.participantId intValue] == _asId) {
            //找到当前正在讲话的人
            asCanva = canva;
            break;
        }
    }
    if (asCanva && self.currentVideos.count > 2 && _asId && _index == 0) {
        //当前正在讲话的人放在大窗口
        [self.currentVideos removeObject:asCanva];
        [self.currentVideos insertObject:asCanva atIndex:1];
    }
    
    if (self.currentVideos.count == 2) {
        //两路流的时候，判断是否有一路为content，如有，则content为大窗口
        XYRTCVideoCanvas *canva = self.currentVideos.firstObject;
        if (canva.layout.isContent) {
            [self.currentVideos exchangeObjectAtIndex:0 withObjectAtIndex:1];
        }
    }
    
    [self updateFrame];
}

- (void)updateFrame {
    NSInteger numbers = self.currentVideos.count;
    if (numbers == 0) {
        return;
    }
    if (kScreen.width < kScreen.height) { //竖屏
        if (_index == 0) {
            //第一页，非对称布局
            _containerView.frame = CGRectMake(0, 0, kScreen.width, kScreen.height);
            if (numbers == 1) {
                //只有1个人，local，大屏展示
                XYCustomVideoView *view = (XYCustomVideoView *)[self.currentVideos.firstObject view];
                [view fullScreen:NO];
            }else if (numbers == 2) {
                //2个人，全屏+右上角小窗口
                XYCustomVideoView *one = (XYCustomVideoView *)[self.currentVideos.firstObject view];
                XYCustomVideoView *two = (XYCustomVideoView *)[self.currentVideos.lastObject view];
                
                [two fullScreen:NO];
                [_containerView sendSubviewToBack:two];
                
                [one moveToPoint:CGPointMake(kScreen.width-80-5, [UIApplication sharedApplication].statusBarFrame.size.height+50) isFixSize:YES isTop:NO landScape:NO];
            }else {
                //多个人
                for (int i = 0; i < numbers; i++) {
                    XYCustomVideoView *view = (XYCustomVideoView *)[self.currentVideos[i] view];
                    CGFloat x = 0;
                    CGFloat y = 0;
                    if (i && i%2 == 0) {
                        x = kScreen.width/2;
                    }
                    if (numbers == 3) {
                        _containerView.frame = CGRectMake(0, (kScreen.height-BIGHEIGHT-SMALLHEIGHT)/2, kScreen.width, BIGHEIGHT+SMALLHEIGHT);
                        if (i == 1) {
                            y = 0;
                        }else {
                            y = BIGHEIGHT;
                        }
                    }else if (numbers <= 5) {
                        _containerView.frame = CGRectMake(0, (kScreen.height-BIGHEIGHT-2*SMALLHEIGHT)/2, kScreen.width, BIGHEIGHT+2*SMALLHEIGHT);
                        if (i == 1) {
                            y = 0;
                        }else if (i < 3) {
                            y = BIGHEIGHT;
                        }else {
                            y = BIGHEIGHT+SMALLHEIGHT;
                        }
                    }else if (numbers <= 7) {
                        _containerView.frame = CGRectMake(0, (kScreen.height-BIGHEIGHT-3*SMALLHEIGHT)/2, kScreen.width, BIGHEIGHT+3*SMALLHEIGHT);
                        if (i == 1) {
                            y = 0;
                        }else if (i < 3) {
                            y = BIGHEIGHT;
                        }else if (i < 5) {
                            y = BIGHEIGHT+SMALLHEIGHT;
                        }else {
                            y = BIGHEIGHT+2*SMALLHEIGHT;
                        }
                    }
                    [view moveToPoint:CGPointMake(x, y) isFixSize:NO isTop:i==1 landScape:NO];
                }
            }
        }else if (_index == 1) {
            //第二页，对称布局，特殊处理
            if (numbers <= 4) {
                XYCustomVideoView *one = (XYCustomVideoView *)[self.currentVideos[0] view];
                XYCustomVideoView *two = (XYCustomVideoView *)[self.currentVideos[1] view];
                if (numbers == 2) {
                    _containerView.frame = CGRectMake(0, (kScreen.height-2*BIGHEIGHT)/2, kScreen.width, 2*BIGHEIGHT);
                    [one updateFrame:CGRectMake(0, 0, kScreen.width, BIGHEIGHT)];
                    [two updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), kScreen.width, BIGHEIGHT)];
                }else if (numbers == 3) {
                    XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                    _containerView.frame = CGRectMake(0, (kScreen.height-3*BIGHEIGHT)/2, kScreen.width, 3*BIGHEIGHT);
                    [one updateFrame:CGRectMake(0, 0, kScreen.width, BIGHEIGHT)];
                    [two updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), kScreen.width, BIGHEIGHT)];
                    [three updateFrame:CGRectMake(0, CGRectGetMaxY(two.frame), kScreen.width, BIGHEIGHT)];
                }else {
                    XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                    XYCustomVideoView *four = (XYCustomVideoView *)[self.currentVideos[3] view];
                    _containerView.frame = CGRectMake(0, (kScreen.height-2*SMALLHEIGHT)/2, kScreen.width, 2*SMALLHEIGHT);
                    [one updateFrame:CGRectMake(0, 0, kScreen.width/2, SMALLHEIGHT)];
                    [two updateFrame:CGRectMake(CGRectGetMaxX(one.frame), 0, kScreen.width/2, SMALLHEIGHT)];
                    [three updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), kScreen.width/2, SMALLHEIGHT)];
                    [four updateFrame:CGRectMake(CGRectGetMaxX(three.frame), CGRectGetMaxY(one.frame), kScreen.width/2, SMALLHEIGHT)];
                }
            }else {
                XYCustomVideoView *one = (XYCustomVideoView *)[self.currentVideos[0] view];
                XYCustomVideoView *two = (XYCustomVideoView *)[self.currentVideos[1] view];
                XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                XYCustomVideoView *four = (XYCustomVideoView *)[self.currentVideos[3] view];
                XYCustomVideoView *five = (XYCustomVideoView *)[self.currentVideos[4] view];
                _containerView.frame = CGRectMake(0, (kScreen.height-3*SMALLHEIGHT)/2, kScreen.width, 3*SMALLHEIGHT);
                [one updateFrame:CGRectMake(0, 0, kScreen.width/2, SMALLHEIGHT)];
                [two updateFrame:CGRectMake(CGRectGetMaxX(one.frame), 0, kScreen.width/2, SMALLHEIGHT)];
                [three updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), kScreen.width/2, SMALLHEIGHT)];
                [four updateFrame:CGRectMake(CGRectGetMaxX(three.frame), CGRectGetMaxY(one.frame), kScreen.width/2, SMALLHEIGHT)];
                [five updateFrame:CGRectMake(0, CGRectGetMaxY(three.frame), kScreen.width/2, SMALLHEIGHT)];
                if (numbers > 5) {
                    XYCustomVideoView *six = (XYCustomVideoView *)[self.currentVideos[5] view];
                    [six updateFrame:CGRectMake(CGRectGetMaxX(five.frame), CGRectGetMaxY(three.frame), kScreen.width/2, SMALLHEIGHT)];
                }
            }
        }else {
            //第三页开始往后，每页6个
            _containerView.frame = CGRectMake(0, (kScreen.height-3*SMALLHEIGHT)/2, kScreen.width, 3*SMALLHEIGHT);
            for (NSInteger i = 0; i < numbers; i++) {
                XYCustomVideoView *view = (XYCustomVideoView *)[self.currentVideos[i] view];
                CGFloat x = 0;
                CGFloat y = 0;
                if (i%2) {
                    x = kScreen.width/2;
                }
                if (i < 2) {
                    y = 0;
                }else if (i < 4) {
                    y = SMALLHEIGHT;
                }else {
                    y = 2*SMALLHEIGHT;
                }
                view.frame = CGRectMake(x, y, kScreen.width/2, SMALLHEIGHT);
            }
        }
    }else {
        CGSize size = [self videoViewSize];
        if (_index == 0) {
            //第一页，非对称布局
            _containerView.frame = CGRectMake(0, 0, kScreen.width, kScreen.height);
            CGFloat x = 5;
            for (int i = 0; i < numbers; i++) {
                XYCustomVideoView *view = (XYCustomVideoView *)[self.currentVideos[i] view];
                if (i == 1 || (i == 0 && numbers == 1)) {
                    //大屏
                    [view fullScreen:YES];
                }else {
                    [view moveToPoint:CGPointMake(x, kScreen.height-85) isFixSize:YES isTop:NO landScape:YES];
                    [_containerView insertSubview:view atIndex:1];
                    x = CGRectGetMaxX(view.frame) + 5;
                }
            }
        }else if (_index == 1) {
            //第二页，对称布局，特殊处理
            if (numbers <= 4) {
                XYCustomVideoView *one = (XYCustomVideoView *)[self.currentVideos[0] view];
                XYCustomVideoView *two = (XYCustomVideoView *)[self.currentVideos[1] view];
                if (numbers == 2) {
                    _containerView.frame = CGRectMake((kScreen.width-2*size.width)/2, (kScreen.height-size.height)/2, 2*size.width, size.height);
                    [one updateFrame:CGRectMake(0, 0, size.width, size.height)];
                    [two updateFrame:CGRectMake(CGRectGetMaxX(one.frame), 0, size.width, size.height)];
                }else if (numbers == 3) {
                    XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                    _containerView.frame = CGRectMake((kScreen.width-2*size.width)/2, (kScreen.height-2*size.height)/2, 2*size.width, 2*size.height);
                    [one updateFrame:CGRectMake((_containerView.xy_width-size.width)/2, 0, size.width, size.height)];
                    [two updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), size.width, size.height)];
                    [three updateFrame:CGRectMake(CGRectGetMaxX(two.frame), CGRectGetMaxY(one.frame), size.width, size.height)];
                }else {
                    XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                    XYCustomVideoView *four = (XYCustomVideoView *)[self.currentVideos[3] view];
                    _containerView.frame = CGRectMake((kScreen.width-2*size.width)/2, (kScreen.height-2*size.height)/2, 2*size.width, 2*size.height);
                    [one updateFrame:CGRectMake(0, 0, size.width, size.height)];
                    [two updateFrame:CGRectMake(CGRectGetMaxX(one.frame), 0, size.width, size.height)];
                    [three updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), size.width, size.height)];
                    [four updateFrame:CGRectMake(CGRectGetMaxX(one.frame), CGRectGetMaxY(one.frame), size.width, size.height)];
                }
            }else {
                XYCustomVideoView *one = (XYCustomVideoView *)[self.currentVideos[0] view];
                XYCustomVideoView *two = (XYCustomVideoView *)[self.currentVideos[1] view];
                XYCustomVideoView *three = (XYCustomVideoView *)[self.currentVideos[2] view];
                XYCustomVideoView *four = (XYCustomVideoView *)[self.currentVideos[3] view];
                XYCustomVideoView *five = (XYCustomVideoView *)[self.currentVideos[4] view];
                _containerView.frame = CGRectMake((kScreen.width-3*size.width)/2, (kScreen.height-2*size.height)/2, 3*size.width, 2*size.height);
                [one updateFrame:CGRectMake(0, 0, size.width, size.height)];
                [two updateFrame:CGRectMake(CGRectGetMaxX(one.frame), 0, size.width, size.height)];
                [three updateFrame:CGRectMake(CGRectGetMaxX(two.frame), 0, size.width, size.height)];
                [four updateFrame:CGRectMake(0, CGRectGetMaxY(one.frame), size.width, size.height)];
                [five updateFrame:CGRectMake(CGRectGetMaxX(four.frame), CGRectGetMaxY(one.frame), size.width, size.height)];
                if (numbers > 5) {
                    XYCustomVideoView *six = (XYCustomVideoView *)[self.currentVideos[5] view];
                    [six updateFrame:CGRectMake(CGRectGetMaxX(five.frame), CGRectGetMaxY(one.frame), size.width, size.height)];
                }
            }
        }else {
            //第三页开始往后，每页6个
            _containerView.frame = CGRectMake((kScreen.width-3*size.width)/2, (kScreen.height-2*size.height)/2, 3*size.width, 2*size.height);
            for (NSInteger i = 0; i < numbers; i++) {
                XYCustomVideoView *view = (XYCustomVideoView *)[self.currentVideos[i] view];
                CGFloat x = 0;
                CGFloat y = 0;
                if (i >= 3) {
                    x = (i-3)*size.width;
                    y = size.height;
                }else {
                    x = i*size.width;
                }
                [view updateFrame:CGRectMake(x, y, size.width, size.height)];
            }
        }
    }
}

- (BOOL)isFullScreen {
#if __clang_major__ > 10
    if (@available(iOS 11.0, *)) {
#else
    if ([UIDevice currentDevice].systemVersion.floatValue >= 11) {
#endif
        CGFloat height = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom;
        return (height > 0);
    } else {
        return NO;
    }
}

- (BOOL)equalLayout:(NemoLayout *)first with:(NemoLayout *)other{
    if ([first.streamID isEqualToString:other.streamID]) {
        return YES;
    }else if ([first.participantId isEqualToString:other.participantId]){
        return YES;
    }else return NO;
}

- (CGSize)videoViewSize {
    CGFloat width = 0;
    CGFloat height = 0;
    if (_videos.count == 2 && _index == 1) {
        if ([self isFullScreen]) {
            width = (kScreen.width-100)/2;
            height = width*9/16;
        }else {
            width = kScreen.width/2;
            height = width*9/16;
        }
    }else if ((_videos.count == 3 || _videos.count == 4) && _index == 1) {
        height = kScreen.height/2;
        width = height*16/9;
    }else {
        if ([self isFullScreen]) {
            width = (kScreen.width-100)/3;
            height = width*9/16;
        }else {
            width = kScreen.width/3;
            height = width*9/16;
        }
    }
    return CGSizeMake(width, height);
}

@end
